<?php
/**
 * Created by PhpStorm.
 * User: Janpoem
 * Date: 2016/8/25
 * Time: 11:52
 */

defined('PRA_AUTH') || define('PRA_AUTH', false);
defined('PRA_SESS_NAME') || define('PRA_SESS_NAME', 'pra_sess');

defined('PRA_LOGIN_PAGE') || define('PRA_LOGIN_PAGE', false);

function pra_get_users()
{
	static $users;
	if (!isset($users)) {
		$usersFile = dirname(__FILE__) . '/auth-users.inc.php';
		if (is_file($usersFile)) {
			$users = require_once($usersFile);
		}
		if (empty($users) || !is_array($users))
			$users = [];
	}
	return $users;
}


function pra_token()
{
	return mt_rand(100000, 999999) . '-' . mt_rand(100000, 999999) . '-' . mt_rand(100000, 999999);
}

function pra_auth(array $post)
{
	global $praLoginError;
	$users = pra_get_users();
	$pUserName = $post['username'] ?? '';
	$pUserName = mb_strtolower($pUserName);
	$pPassword = $post['password'] ?? '';
	if (!isset($users[$pUserName])) {
		return false;
	}
	$uPassword = $users[$pUserName];
	if (empty($uPassword)) {
		return false;
	}
	if (!password_verify($pPassword, $uPassword)) {
		return false;
	} else {
		$ref = 'index.php';
		if (!empty($_SESSION['ref_url'])) {
			$ref = $_SESSION['ref_url'];
			unset($_SESSION['ref_url']);
		}
		$_SESSION['user_name'] = $pUserName;
		$_SESSION['user_info'] = [
			'agent'  => $_SERVER['HTTP_USER_AGENT'],
			'remote' => $_SERVER['REMOTE_ADDR'],
		];
		header('Location: ' . $ref);
		return true;
	}
}

function pra_password_generate($password)
{
	$options = [
		'cost' => 12,
	];
	return password_hash(md5($password), PASSWORD_BCRYPT, $options);
}

function pra_session_init()
{
	session_name(PRA_SESS_NAME);
	session_start();
	$users = pra_get_users();

	if (empty($users))
		exit('Enabled user authentication, but undefined users!');

	if (!PRA_LOGIN_PAGE) {
		if (!isset($_SESSION['user_name']) || !isset($users[$_SESSION['user_name']]) || !pra_session_verify()) {
			header('Location: login.php');
			exit('Invalid user!');
		}
	}
}

function pra_session_verify()
{
	$info = $_SESSION['user_info'] ?? [];
	if (empty($info))
		return false;
	$agent = $info['agent'];
	$remote = $info['remote'];
	if ($agent !== $_SERVER['HTTP_USER_AGENT'])
		return false;
	if ($remote !== $_SERVER['REMOTE_ADDR'])
		return false;
	return true;
}

if (PRA_AUTH) {
	pra_session_init();
}



